/**
 * Created by apple on 2017/6/9.
 */
var DBFactory = require('../db/mysql_db');
var async = require('async');
var agentDao = module.exports;


//添加代理
agentDao.addAgent = function(data,cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    var sql = "select app_sid,lvl from app_agent where app_sid = ? and lvl = ? limit 1";
    var vaule = [data.app_sid,data.lvl];
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            function (callback) {//先查是否存在该代理
                connection.query(sql,vaule,function (err,result) {
                    var agentInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, agentInfo);
                });
            },

            function (agentInfo,callback) {
                if(agentInfo) {
                    callback('该agent已存在!',null);
                    return;
                }//到这里说明不存在，则插入
                connection.query('insert into app_agent set ?',data,function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows <= 0){
                        callback('操作失败',null);
                        console.log('插入app_agent表失败');
                        return;
                    }
                    callback(null,'成功');
                });
            },

            function (res,callback) {
                if(!res) {
                    callback('操作失败',null);
                    return;
                }//到这里说明插入app_agent表成功，再去更新下apps表的vip_items字段
                connection.query('update apps set agent_items = agent_items + 1 where sid = ?',data.app_sid,function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'操作成功');
                    }else {
                        callback('操作失败',null);
                        console.log('操作apps表失败')
                    }
                });
            }

        ],function (err,res) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });
}

//修改代理
agentDao.updateAgent = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }

    var account = data.account;
    var adm_uid = data.adm_uid;
    delete data.account;
    delete data.adm_uid;
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            //先查该代理的原参数
            function (callback) {
                connection.query('select * from app_agent where app_sid = ? and lvl = ? limit 1',[data.app_sid,data.lvl],function (err,result) {
                    var agentInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, agentInfo);
                });
            },

            //判断是否存在，存在修改
            function (agentInfo,callback) {
                if(!agentInfo) {
                    callback('该agent不存在!',null);
                    return;
                }
                connection.query('update app_agent set ? where app_sid = ? and lvl = ? ',[data,data.app_sid,data.lvl],function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,agentInfo);
                        return;
                    }
                    callback('操作失败',null);
                    console.log('修改代理时更改app_agent表失败');
                });
            },

            //修改成功，插入admin_log记录
            function (agentInfo,callback) {
                if(!agentInfo) {
                    callback('操作失败',null);
                    return;
                }

                var adminInfo = {
                    account: account,
                    adm_uid: adm_uid,
                    type: 5,
                    detail: '代理变更：'
                };

                delete data.app_sid;
                delete data.lvl;

                //记录修改的参数
                for(var p in data){
                    adminInfo.detail += p + ':' + agentInfo[p] + '->' + data[p] + ',';
                }

                connection.query('insert into admin_log set ? ',adminInfo,function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'操作成功');
                        return;
                    }
                    callback('操作失败',null);
                    console.log('更改代理时操作admin_log表失败')

                });
            }

        ],function (err,res) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}



//查询代理
agentDao.agentList = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    var sql = 'select app_sid,lvl,name,score,status,commission_rate1,commission_rate2,commission_rate3 from app_agent where app_sid = ?';
    var value = [data.app_sid];
    if(data.status){
        sql += ' and status = ? ';
        value.push(data.status);
    }
    if(data.lvl){
        sql += 'AND lvl = ? ';
        value.push(data.lvl);
    }
    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null,result);
        }
    );
}